{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-1-d32d850502f2>:9: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "\n",
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了兼顾性能和代码复杂度，决定采用两个隐层的神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9751\n"
     ]
    }
   ],
   "source": [
    "batch_size = 100\n",
    "# 计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples\n",
    "x = tf.placeholder(tf.float32, [None, 784], name='x_input')\n",
    "y = tf.placeholder(tf.float32, [None, 10], name='y_input')\n",
    "\n",
    "\n",
    "W1 = tf.Variable(tf.truncated_normal([784, 500], stddev=0.1), name='W1')\n",
    "b1 = tf.Variable(tf.zeros([500]) + 0.1, name='b1')\n",
    "L1 = tf.nn.tanh(tf.matmul(x, W1) + b1, name='L1')\n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([500, 300], stddev=0.1), name='W2')\n",
    "b2 = tf.Variable(tf.zeros([300]) + 0.1, name='b2')\n",
    "L2 = tf.nn.tanh(tf.matmul(L1, W2) + b2, name='L2')\n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([300, 10], stddev=0.1), name='W3')\n",
    "b3 = tf.Variable(tf.zeros([10]) + 0.1, name='b3')\n",
    "\n",
    "y_pred = tf.matmul(L2, W3) + b3\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pred)\n",
    ")\n",
    "\n",
    "\n",
    "# 梯度下降\n",
    "train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "# Train\n",
    "for _ in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})\n",
    "\n",
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "性能已经达到97%了，接下来对学习率进行调参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9803\n"
     ]
    }
   ],
   "source": [
    "batch_size = 100\n",
    "# 计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples\n",
    "x = tf.placeholder(tf.float32, [None, 784], name='x_input')\n",
    "y = tf.placeholder(tf.float32, [None, 10], name='y_input')\n",
    "\n",
    "\n",
    "W1 = tf.Variable(tf.truncated_normal([784, 500], stddev=0.1), name='W1')\n",
    "b1 = tf.Variable(tf.zeros([500]) + 0.1, name='b1')\n",
    "L1 = tf.nn.tanh(tf.matmul(x, W1) + b1, name='L1')\n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([500, 300], stddev=0.1), name='W2')\n",
    "b2 = tf.Variable(tf.zeros([300]) + 0.1, name='b2')\n",
    "L2 = tf.nn.tanh(tf.matmul(L1, W2) + b2, name='L2')\n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([300, 10], stddev=0.1), name='W3')\n",
    "b3 = tf.Variable(tf.zeros([10]) + 0.1, name='b3')\n",
    "\n",
    "y_pred = tf.matmul(L2, W3) + b3\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pred)\n",
    ")\n",
    "\n",
    "\n",
    "# 梯度下降\n",
    "train_step = tf.train.GradientDescentOptimizer(0.4).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "# Train\n",
    "for _ in range(4000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})\n",
    "\n",
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里实际上进行了多次调参，当学习率为0.3和0.5时，正确率分别为：0.9758和0.9738"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当学习率为0.4时，模型的性能已经达到98%的标准了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
